<script lang="tsx">
import { defineComponent, ref, h, compile, computed, Text } from "vue";
import { useRoute, useRouter, RouteRecordRaw } from "vue-router";
import type { RouteMeta } from "vue-router";
import { useAppStore } from "@/store";
import { listenerRouteChange } from "@/utils/route-listener";
import { openWindow, regexUrl } from "@/utils";
import useMenuTree from "./useMenuTree";

export default defineComponent({
  emit: ["collapse"],
  setup() {
    const appStore = useAppStore();
    const router = useRouter();
    const route = useRoute();
    const { menuTree } = useMenuTree();
    const collapsed = computed({
      get() {
        if (appStore.device === "desktop") return appStore.menuCollapse;
        return false;
      },
      set(value: boolean) {
        appStore.updateSettings({ menuCollapse: value });
      },
    });

    const topMenu = computed(() => appStore.topMenu);
    const openKeys = ref<string[]>([]);
    const selectedKey = ref<string[]>([]);

    // 调试方法：检查路由是否存在
    const checkRouteExists = (name: string) => {
      const exists = router.hasRoute(name);

      // 如果不存在，尝试找到所有可用的路由
      if (!exists) {
        // console.log('所有已注册的路由:');
        router.getRoutes().forEach((route) => {});
      }

      return exists;
    };

    const goto = (item: RouteRecordRaw) => {
      // Open external link
      if (item.path && regexUrl.test(item.path)) {
        openWindow(item.path);
        selectedKey.value = [item.name as string];
        return;
      }
      // 检查 meta 是否存在
      if (!item.meta) {
        // 尝试直接跳转
        try {
          router.push({
            name: item.name,
          });
        } catch (error) {
          console.error("路由跳转失败:", error);
        }
        return;
      }

      // 检查路由是否存在
      if (!checkRouteExists(item.name as string)) {
        // 尝试通过路径导航
        try {
          router.push({
            path: item.path,
          });
          return;
        } catch (pathError) {
          console.error("通过路径导航也失败:", pathError);
          return;
        }
      }

      // Eliminate external link side effects
      const { hideInMenu, activeMenu } = item.meta as RouteMeta;
      if (route.name === item.name && !hideInMenu && !activeMenu) {
        selectedKey.value = [item.name as string];
        return;
      }
      // Trigger router change
      router.push({
        name: item.name,
      });
    };

    const findMenuOpenKeys = (target: string) => {
      const result: string[] = [];
      let isFind = false;
      const backtrack = (item: RouteRecordRaw, keys: string[]) => {
        if (item.name === target) {
          isFind = true;
          result.push(...keys);
          return;
        }
        if (item.children?.length) {
          item.children.forEach((el) => {
            backtrack(el, [...keys, String(el.name || "")]);
          });
        }
      };
      menuTree.value.forEach((el: RouteRecordRaw) => {
        if (isFind) return; // Performance optimization
        backtrack(el, [String(el.name || "")]);
      });
      return result;
    };

    listenerRouteChange((newRoute) => {
      if (!newRoute.meta) return;

      const { requiresAuth, activeMenu, hideInMenu } = newRoute.meta;
      if (requiresAuth && (!hideInMenu || activeMenu)) {
        const menuOpenKeys = findMenuOpenKeys(
          activeMenu || String(newRoute.name || "")
        );

        const keySet = new Set([...menuOpenKeys, ...openKeys.value]);
        openKeys.value = [...keySet];

        selectedKey.value = [
          activeMenu || menuOpenKeys[menuOpenKeys.length - 1],
        ];
      }
    }, true);

    const setCollapse = (val: boolean) => {
      if (appStore.device === "desktop")
        appStore.updateSettings({ menuCollapse: val });
    };

    // 固定菜单项
    const fixedMenu = [
      {
        name: "fixed-dashboard",
        icon: "icon-dashboard",
        title: "工作台",
        children: [
          {
            name: "fixed-dashboard-workplace",
            title: "工作台",
            path: "/dashboard/workplace/Home",
          },
        ],
      },
      {
        name: "fixed-workflow",
        icon: "icon-storage",
        title: "流程管理",
        children: [
          {
            name: "fixed-workflow-designer",
            title: "流程设计",
            path: "/workflow/designer",
          },
          {
            name: "fixed-view-designer",
            title: "视图设计",
            // path: "/workflow/viewDesigner",
            path: "/workflow/viewDesigner",
          },
        ],
      },
    ];

    // 修改renderSubMenu，支持渲染固定菜单
    const renderSubMenu = () => {
      function travel(_route: RouteRecordRaw[], nodes = []) {
        if (_route) {
          _route.forEach((element) => {
            try {
              // 确保 meta 存在
              if (!element.meta) {
                element.meta = { locale: String(element.name || "未命名") };
              }
              // This is demo, modify nodes as needed
              const icon = element?.meta?.icon
                ? () => h(compile(`<${element?.meta?.icon}/>`))
                : null;

              // 直接使用locale值，不通过compile处理
              const title = element?.meta?.locale || element?.meta?.title || "";

              const node =
                element?.children && element?.children.length !== 0 ? (
                  <a-sub-menu
                    key={String(element?.name || "")}
                    v-slots={{
                      icon,
                      title: () => title,
                    }}
                  >
                    {travel(element?.children)}
                  </a-sub-menu>
                ) : (
                  <a-menu-item
                    key={String(element?.name || "")}
                    v-slots={{ icon }}
                    onClick={() => goto(element)}
                  >
                    {title}
                  </a-menu-item>
                );
              nodes.push(node as never);
            } catch (error) {
              console.error("处理菜单项时出错:", error);
            }
          });
        }
        return nodes;
      }
      // 先渲染动态菜单，再渲染固定菜单
      const nodes = travel(menuTree.value);
      // 渲染固定菜单
      fixedMenu.forEach((fixed) => {
        const icon = fixed.icon ? () => h(compile(`<${fixed.icon}/>`)) : null;
        nodes.push(
          <a-sub-menu
            key={fixed.name}
            v-slots={{ icon, title: () => fixed.title }}
          >
            {fixed.children.map((child) => (
              <a-menu-item
                key={child.name}
                onClick={() => router.push(child.path)}
              >
                {child.title}
              </a-menu-item>
            ))}
          </a-sub-menu>
        );
      });
      return nodes;
    };

    return () => (
      <a-menu
        mode={topMenu.value ? "horizontal" : "vertical"}
        v-model:collapsed={collapsed.value}
        v-model:open-keys={openKeys.value}
        show-collapse-button={appStore.device !== "mobile"}
        auto-open={false}
        selected-keys={selectedKey.value}
        auto-open-selected={true}
        level-indent={34}
        onCollapse={setCollapse}
      >
        {renderSubMenu()}
      </a-menu>
    );
  },
});
</script>

<style lang="less" scoped>
:deep(.arco-menu-inner) {
  .arco-menu-inline-header {
    display: flex;
    align-items: center;
  }

  .arco-icon {
    &:not(.arco-icon-down) {
      font-size: 18px;
    }
  }
}
</style>
